<template>
  <div class="clearfix">
    <a-upload
      :accept="accept"
      :remove="handleRemove"
      listType="picture-card"
      :fileList="fileList"
      :multiple="true"
      @preview="handlePreview"
      :customRequest="customRequest"
      :openFileDialogOnClick="fileList.length < fileLength"
    >
      <div v-if="fileList.length < fileLength" >
        <a-icon type="plus" />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :title="previewFileName" width="80%":footer="null" @cancel="handlePreviewCancel">
        <av-line v-if="getFileType(previewUrl) == 'music'" :audio-src="previewUrl"></av-line>
        <iframe  v-else-if="getFileType(previewUrl)=='excel' || getFileType(previewUrl)=='text'" :src="previewUrl" frameborder="0" width="100%" height="500px" scrolling="auto"></iframe>
        <iframe  v-else-if="getFileType(previewUrl)=='pdf'" :src="previewUrl" frameborder="0" width="100%" height="500px" scrolling="auto">您的浏览器不支持pdf预览</iframe>
        <video v-else-if="getFileType(previewUrl)=='video'"  id="myVideo" class="video-js" style="width:100%;height: 600px">
          <source
            :src="previewUrlVideo"
            type="video/mp4"/>
        </video>
        <img  :large="previewUrl"  v-else-if="getFileType(previewUrl) == 'img'" style="height: 600px" :src="previewUrl" :preview="previewUrl"/>
        <div v-else> 文件不支持预览</div>
    </a-modal>

  </div>
</template>


<script>
  import AvLine from 'vue-audio-visual/src/components/AvLine';
  import video from 'video.js';
  import 'video.js/dist/video-js.min.css'
  import { isSameDomain, isURL } from '../../utils/validate'
  import AkFilePreview from '../../components/akfh/file-preview/AkFilePreview'
  import {appApiBaseUrl} from '../../config/constant.config';
  import {concatUrl, randomUUID} from '../../utils/util';
  import { downFile, getAction, uploadFile } from '../../api/manage'
  import {fileManager} from "../../api/url"
  export default {
    components:{AkFilePreview, AvLine},
    name: 'AkUpload',
    props: {
      value: {
        type: String,
        default: '',
        required: false
      },
      disabled:{
        type:Boolean,
        default:false,
        required:false,
      },
      type:String,
      fileLength:{
        type: Number,
        default: 10,
        required: false
      },
      updateFileName:{
        type:Boolean,
        default:true,
        required:false,
      }
    },
    data:function() {
      return{
        importPercent:0,//上传百分
        importLoading:false, //正在上传
        accept:'*',
        // 预览可见
        previewVisible: false,
        // 预览url
        previewUrl: '',
        // 预览文件名
        previewFileName:'',
        previewUrlVideo:'',
        previewHtml:'',
        fileList: [],
        baseUrl:'',
        myPlayer:{},

      }
    },

    mounted(){
     this.baseUrl = concatUrl(appApiBaseUrl,fileManager.fileBaseUrl);
     if(this.value){
       this.fileList = this.handleFileListStringToFileList(this.value);
     }else{
       this.fileList = [];
     }
     getAction(fileManager.fileUploadTypeUrl, {type:this.type})
       .then(res=>{
         if(res.success){
           this.accept=res.result;
         }
       })

    },
    watch: {
      value (val) {
        if(val){
          this.fileList=this.handleFileListStringToFileList(val);
        }else{
          this.fileList =[];
        }

      },
    },
    methods:{
      customRequest(request){
        let url = fileManager.uploadUrl;

        let file = request.file;
        let formData = new FormData();
        let filename = request.filename||'file';
        let data = request.data || {};
        if(typeof data == "function"){
          data = data(file)||{};
        }
        for (let dataKey in data) {
          formData.append(dataKey, data[dataKey]);
        }
        formData.append(filename, file);
        formData.append("type", this.type);
        formData.append("updateFileName", this.updateFileName);
        this.importLoading = true;
        let fileRealName = file.name;
        let f = {
          uid:randomUUID(),
          name:fileRealName,
          originFileObj:file,
          status:'uploading',
          percent:0,
          size:file.size,
          lastModified:file.lastModified,
          lastModifiedDate:undefined,
          thumbUrl:null,
          type:file.type,
          originUrl:'',
        }
        this.fileList.push(f);
        uploadFile(url, formData, (event)=>{
          if(event.total){
            this.importPercent = (event.loaded*1.0/event.total*100);
            f.percent = this.importPercent;
            this.fileList = [...this.fileList];
          }
        }).then(res=>{
          if(res.success){
            let t = res.result[0];
            this.$message.success('文件上传成功');
            f.status = "done";
            f.name = t;
            f.originUrl = t;
            f.thumbUrl = this.getFileThumbUrl(t);
            f.url=isURL(t)?t:concatUrl(this.baseUrl,t);
            this.fileList = [...this.fileList];
            this.handleFileChange(this.fileList);
          }
        })
          .finally(()=>{
            this.importLoading = false;
          });
        return f;
      },
      // 删除文件
      handleRemove(file){
        if(this.disabled){
          this.$message.warning("此文件不允许删除");
          return ;
        }
        this.fileList = this.fileList.filter(t=>t!=file);
        this.handleFileChange(this.fileList);
      },
      handleFileListStringToFileList(val){
        let fileArray = [];
        let urlArrays = val.split(",");
        for (let i = 0; i < urlArrays.length; i++) {
          if (urlArrays[i]) {
            fileArray.push({
              uid:randomUUID(),
              name:urlArrays[i],
              status:'done',
              percent:0,
              thumbUrl:this.getFileThumbUrl(urlArrays[i]),
              originUrl:urlArrays[i],
            });
          }

        }
        return fileArray;
      },
      handlePreviewCancel() {
        this.previewVisible = false;
        if(this.getFileType(this.previewUrl)=='video'){
          this.myPlayer.pause();
        }
      },
      handlePreview(file) {

        let url = file.originUrl||file.url || file.thumbUrl;
        let type = this.getFileType(url);
        let previewUrl = isURL(url)?url:concatUrl(concatUrl(appApiBaseUrl, fileManager.filePrewUrl), url);
        let downUrl = isURL(url)?url:concatUrl(this.baseUrl, url);
        this.previewFileName = url;
        if(type == 'video'){

          if(isSameDomain(window.location.href, downUrl)){
            this.previewUrlVideo= downUrl;
            this.previewUrl = downUrl;
            this.$nextTick(()=>{
              this.myPlayer = video('myVideo', {
                //确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
                controls: true,
                //自动播放属性,muted:静音播放
                autoplay: "muted",
                //建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
                preload: "auto",
                // //设置视频播放器的显示宽度（以像素为单位）
                // width: "800px",
                // //设置视频播放器的显示高度（以像素为单位）
                // height: "400px"
              });
            })
          }
          else {
            downFile(downUrl).then(res=>{
              this.previewUrlVideo = URL.createObjectURL(res.data);
              this.$nextTick(()=>{
                this.myPlayer = video('myVideo', {
                  //确定播放器是否具有用户可以与之交互的控件。没有控件，启动视频播放的唯一方法是使用autoplay属性或通过Player API。
                  controls: true,
                  //自动播放属性,muted:静音播放
                  autoplay: "muted",
                  //建议浏览器是否应在<video>加载元素后立即开始下载视频数据。
                  preload: "auto",
                  // //设置视频播放器的显示宽度（以像素为单位）
                  // width: "800px",
                  // //设置视频播放器的显示高度（以像素为单位）
                  // height: "400px"
                });
              })
            }).catch(e=>{
              console.warn(e);
              this.$message.warn("文件下载网络错误");
            });
          }

        }
        if(type=='word'|| type=='excel' ){
          this.previewUrl = previewUrl;
        }
        if(type == 'text' || type == 'pdf'|| type=='music'){
          this.previewUrl = downUrl;
        }
        this.previewVisible = true;
      },
      handleFileChange(fileList) {
        if(fileList){
          this.$emit("change", fileList.map(t=>t.originUrl).join(","));
        }else {
          this.$emit("change", "");
        }
      },
      getFileType(name){

        let suffix = name.substring(name.lastIndexOf(".")+1).toLocaleLowerCase();
        if(suffix == 'mp3'||suffix == 'wma' || suffix=='midi'){
          return "music";
        }
        if(suffix == 'xls'||suffix == 'xlsx'){
          return "excel";
        }
        if(suffix == 'pptx'||suffix == 'ppt'){
          return "ppt";
        }
        if(suffix == 'doc'||suffix == 'docx'){
          return "excel";
        }
        if(suffix == 'avi'||suffix == 'mov'||suffix == 'rmvb'||suffix == 'rm'||suffix == 'flv'||suffix == 'mp4'||suffix == '3gp'){
          return "video";
        }
        if(suffix == 'rar'||suffix == 'tar'||suffix == 'zip'||suffix == 'gz'||suffix == 'cab'||suffix == 'arj'||suffix == 'bz2'
          ||suffix == 'lzh'||suffix == 'jar'||suffix == 'ace'||suffix == 'iso'||suffix == '7-zip'||suffix == 'z'){
          return "compress";
        }
        if(suffix == 'txt'||suffix == 'conf'||suffix == 'html'||suffix == 'js'||suffix == 'css'||suffix == 'jsp'){
          return "text";
        }
        if(suffix == 'pdf'){
          return "pdf";
        }
        if(suffix == 'png'||suffix == 'jpg'||suffix == 'jpeg'||suffix == 'gif'||suffix == 'bmp'||suffix == 'ico'
          ||suffix == 'svg'){
          return "img";
        }
        return "file";
      },
      getFileThumbUrl(name){
        let type = this.getFileType(name);
        if(type != "img" && type != 'file'){
          return concatUrl(appApiBaseUrl, "/file/icon/"+type+".png");
        }
        if(type == 'img'){
          return concatUrl(this.baseUrl, name);
        }
        return concatUrl(appApiBaseUrl, "/file/icon/file.png");
      }

    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>
